import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import os
import time
from typing import List
from web2pdfs import capture_scroll_screenshot_and_save_pdf

class UiUrl2Pdf:
    '界面类'
    def __init__(self, root):
        self.root = root
        self.root.title("页面捕获工具")
        self.root.geometry("600x300")
        
        # 存储历史记录的列表
        self.history: List[str] = []
        
        # 加载历史记录
        self.load_history()
        
        # 创建界面元素
        self.create_widgets()
    
    def load_history(self):
        """从文件加载历史记录"""
        try:
            if os.path.exists("url_history.txt"):
                with open("url_history.txt", "r", encoding="utf-8") as f:
                    self.history = [line.strip() for line in f.readlines() if line.strip()]
        except Exception as e:
            print(f"加载历史记录失败: {e}")
    
    def save_history(self):
        """保存历史记录到文件"""
        try:
            with open("url_history.txt", "w", encoding="utf-8") as f:
                for url in self.history:
                    f.write(url + "\n")
        except Exception as e:
            print(f"保存历史记录失败: {e}")
    
    def create_widgets(self):
        """创建所有界面元素"""
        # URL输入部分
        url_frame = ttk.LabelFrame(self.root, text="网址", padding=(10, 5))
        url_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.url_var = tk.StringVar()
        self.url_combobox = ttk.Combobox(
            url_frame, 
            textvariable=self.url_var,
            values=self.history,
            width=50
        )
        self.url_combobox.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 5))
        
        # 添加URL按钮
        add_url_btn = ttk.Button(
            url_frame, 
            text="删除记录", 
            command=self.remove_url_from_history
        )
        add_url_btn.pack(side=tk.RIGHT)
        
        # PDF保存路径部分
        pdf_frame = ttk.LabelFrame(self.root, text="保存路径", padding=(10, 5))
        pdf_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.pdf_path_var = tk.StringVar()
        pdf_entry = ttk.Entry(
            pdf_frame, 
            textvariable=self.pdf_path_var,
            width=50
        )
        pdf_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 5))
        
        # 浏览按钮
        browse_btn = ttk.Button(
            pdf_frame, 
            text="浏览...", 
            command=self.browse_pdf_path
        )
        browse_btn.pack(side=tk.RIGHT)
        
        # 执行按钮
        execute_frame = ttk.Frame(self.root, padding=(10, 5))
        execute_frame.pack(fill=tk.X, padx=10, pady=10)
        
        self.execute_btn = ttk.Button(
            execute_frame,
            text="执行",
            command=self.execute_task,
            state=tk.NORMAL
        )
        self.execute_btn.pack(pady=5)
        
        # 进度条
        self.progress_frame = ttk.LabelFrame(self.root, text="进度", padding=(10, 5))
        self.progress_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(
            self.progress_frame,
            variable=self.progress_var,
            maximum=100,
            mode='determinate'
        )
        self.progress_bar.pack(fill=tk.X, expand=True)
        
        # 状态标签
        self.status_var = tk.StringVar()
        self.status_label = ttk.Label(
            self.progress_frame,
            textvariable=self.status_var,
            foreground="blue"
        )
        self.status_label.pack()
    
    def add_url_to_history(self):
        """将当前URL添加到历史记录"""
        url = self.url_var.get().strip()
        if not url:
            messagebox.showwarning("警告", "请输入有效的网址")
            return
        
        # 如果URL不在历史记录中，则添加
        if url not in self.history:
            self.history.insert(0, url)
            self.url_combobox['values'] = self.history
            self.save_history()
            messagebox.showinfo("成功", "网址已添加到历史记录")
        else:
            messagebox.showinfo("提示", "该网址已在历史记录中")

    def remove_url_from_history(self):
        """将当前URL记录删除"""
        url = self.url_var.get().strip()
        if not url:
            return
        
        if url in self.history:
            self.history.remove(url)
            self.url_combobox["values"] = self.history
            self.save_history()
    
    def browse_pdf_path(self):
        """浏览并选择PDF保存路径"""
        file_path = filedialog.asksaveasfilename(
            defaultextension=".pdf",
            filetypes=[("PDF文件", "*.pdf"), ("所有文件", "*.*")]
        )
        if file_path:
            self.pdf_path_var.set(file_path)
    
    def execute_task(self):
        """执行任务（模拟）"""
        url = self.url_var.get().strip()        
        pdf_path = self.pdf_path_var.get().strip()
        
        if not url:
            messagebox.showwarning("警告", "请输入有效的网址")
            return
        
        if not url.startswith(('http://','https://')):
            messagebox.showwarning("警告", "请输入有效的网址")
            return
        
        if not pdf_path:
            messagebox.showwarning("警告", "请选择PDF保存路径")
            return
        
        # 禁用执行按钮
        self.execute_btn.config(state=tk.DISABLED)
        self.status_var.set("任务开始执行...")
        self.root.update()
        
        # 模拟任务执行过程
        try:
            capture_scroll_screenshot_and_save_pdf(url=url,output_pdf=pdf_path,scroll_step=800,max_scrolls=1500,timeout=10,max_page_height=1500)

            for i in range(1, 101):
                time.sleep(0.05)  # 模拟耗时操作
                self.progress_var.set(i)
                self.status_var.set(f"处理中... {i}%")
                self.root.update()
            
            # 任务完成
            self.status_var.set(f"任务完成! 网址: {url}, 保存到: {pdf_path}")
            messagebox.showinfo("成功", "任务执行完成!")
            
            # 将URL添加到历史记录（如果不在其中）
            if url not in self.history:
                self.history.insert(0, url)
                self.url_combobox['values'] = self.history
                self.save_history()
                
        except Exception as e:
            messagebox.showerror("错误", f"执行任务时出错: {e}")
            self.status_var.set("任务执行失败")
        finally:
            self.execute_btn.config(state=tk.NORMAL)

if __name__ == "__main__":
    root = tk.Tk()
    app = UiUrl2Pdf(root)
    root.mainloop()